package com.gdk.ksoft.ui.sales;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.assembly.dbhelper.PsaleDbHelper;
import com.gdk.ksoft.data.entry.tables.SaleBuyOtherLevelTable;
import com.gdk.ksoft.data.entry.tables.SaleBuyOtherTable;
import com.gdk.ksoft.data.entry.tables.ShoppingCartGoodsTable;
import com.gdk.ksoft.ui.sales.adapters.GiveOtherAdapter;
import com.gdk.ksoft.assembly.dialog.GiveSelfChangeNumberDialog;
import com.gdk.ksoft.assembly.widget.InnerListView;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

import java.util.ArrayList;
import java.util.List;

/**
 * 买赠它品的页面
 */
public class GiveOtherActivity extends Activity {

    @ViewInject(R.id.pgiveOther_txtThemeTitle)private TextView txtThemeTitle;//主题标题
    @ViewInject(R.id.pgiveOther_txtThemeDescription)private TextView txtThemeDescription;//主题描述
    @ViewInject(R.id.pgiveOther_imgIcon)private ImageView imgThemeIcon;//主题图标
    @ViewInject(R.id.pgiveOther_txtTotalMoney)private TextView txtTotalMoney;//总金额
    @ViewInject(R.id.pgiveOther_txtSelfCount)private TextView txtSelfCount;//本品总数
    @ViewInject(R.id.pgiveOther_txtGiveCount)private TextView txtGiveCount;//赠品总数
    @ViewInject(R.id.pgiveOther_listSelfGoods)private InnerListView listSelfGoods;//本品商品数据列表
    @ViewInject(R.id.pgiveOther_listGiveGoods)private InnerListView listGiveGoods;//赠送本品的数据列表

    private int kh_id,shdz_id;//客户ID，送货地址ID
    private int cx_id = 0;//促销ID号
    private String priceName;//客户价格名称
    private String cx_target = String.valueOf(System.currentTimeMillis());//促销标识
    private SaleBuyOtherTable saleBuyOther;//买赠它品促销对象
    private List<SaleBuyOtherLevelTable> saleLevelList;//赠送等级列表
    private List<ShoppingCartGoodsTable> selflist = new ArrayList<>(),
            givelist = new ArrayList<>();
    private GiveOtherAdapter selfAdapter = null,
            giveAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_give_other);
        ViewUtils.inject(this);
        selfAdapter = new GiveOtherAdapter(this,selflist);
        giveAdapter = new GiveOtherAdapter(this,givelist);
        listSelfGoods.setAdapter(selfAdapter);
        listGiveGoods.setAdapter(giveAdapter);
        Intent intent = getIntent();
        if(intent!=null){//初始化页面操作
            kh_id = intent.getIntExtra("kh_id",0);
            shdz_id = intent.getIntExtra("shdz_id",0);
            priceName = intent.getStringExtra("priceName");
            cx_id = intent.getIntExtra("cx_id", 0);
            initActivity(this,cx_id,kh_id,shdz_id);
        }

    }

    /**
     * 初始化页面操作
     * @param context
     */
    public void initActivity(final Context context,final int saleId,final int kh_id,final int shdz_id){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog = null;
            private List<ShoppingCartGoodsTable> listSelf = null;
            private List<ShoppingCartGoodsTable> listGift = null;
            private String errMessage = null,description = "";

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    DbUtils dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
                    saleBuyOther = dbUtils.findFirst(Selector.from(SaleBuyOtherTable.class).where("id","=",saleId));
                    saleLevelList = dbUtils.findAll(Selector.from(SaleBuyOtherLevelTable.class).where("cx_id","=",saleId).orderBy("gmjs",true));
                    for(SaleBuyOtherLevelTable item : saleLevelList) description += item.jtmc + " ";
                    listSelf = PsaleDbHelper.findAllBuyOtherGoods(dbUtils, kh_id, shdz_id, saleId);
                    listGift = PsaleDbHelper.findAllBuyOtherGiftGoods(dbUtils,kh_id,shdz_id,saleId);
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog != null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    Toast.makeText(context, "加载失败!", Toast.LENGTH_SHORT).show();
                    ((Activity)context).finish();
                    return;
                }
                if(saleBuyOther!=null){
                    txtThemeDescription.setText(description);
                    txtThemeTitle.setText(saleBuyOther.zt);
                }
                selflist.addAll(listSelf);
                selfAdapter.notifyDataSetChanged();
                givelist.addAll(listGift);
                giveAdapter.notifyDataSetChanged();
            }
        }.execute();
    }

    @OnItemClick(value = {R.id.pgiveOther_listSelfGoods,R.id.pgiveOther_listGiveGoods})
    public void onItemClick(AdapterView<?> av,View view, final int position,long itemId){
        switch(av.getId()){
            case R.id.pgiveOther_listSelfGoods:
                final ShoppingCartGoodsTable item = selflist.get(position);
                new GiveSelfChangeNumberDialog(this,true,item,new GiveSelfChangeNumberDialog.OnValueChangedListener(){
                    @Override
                    public void onValueChanged(int pieceNum, int singleNum,float price) {
                        ShoppingCartGoodsTable value = item;
                        value.xsdwsl = pieceNum;
                        value.xsdwss = singleNum;
                        value.hsdwsl = pieceNum * item.hsgx + singleNum;
                        value.bzxsdwj = price*item.hsgx;
                        value.cx_bz = cx_target;
                        value.yfje = Float.valueOf(FormatUtils.exactNumber(pieceNum * value.bzxsdwj + singleNum * value.bzxsdwj / value.hsgx, "0.00"));
                        value.lx = 10;//买赠它品
                        selflist.set(position,value);
                        selfAdapter.notifyDataSetChanged();
                        makeAccount(selflist, txtSelfCount,0);//做数据统计
                    }
                }).show();
                break;
            case R.id.pgiveOther_listGiveGoods:
                final ShoppingCartGoodsTable item1 = givelist.get(position);
                new GiveSelfChangeNumberDialog(this,false,item1,new GiveSelfChangeNumberDialog.OnValueChangedListener(){
                    @Override
                    public void onValueChanged(int pieceNum, int singleNum,float price) {
                        ShoppingCartGoodsTable value = item1;
                        value.xsdwsl = pieceNum;
                        value.xsdwss = singleNum;
                        value.cx_bz = cx_target;
                        value.hsdwsl = pieceNum * item1.hsgx + singleNum;
                        value.yfje = 0;//赠品金额为0   Float.valueOf(FormatUtils.exactNumber(pieceNum*item1.bzxsdwj+singleNum*item1.bzxsdwj/item1.hsgx,"0.00"));
                        value.lx = 12;//买赠本品赠品
                        givelist.set(position,value);
                        giveAdapter.notifyDataSetChanged();
                        makeAccount(givelist, txtGiveCount,1);//做数据统计
                    }
                }).show();
                break;
        }
    }


    /**
     * 界面控件的点击事件
     * @param view
     */
    @OnClick(value={R.id.pgiveOther_txtSubmit})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pgiveOther_txtSubmit://提交数据
                if(!makeTotalAccount()){
                    Toast.makeText(this,"该赠送数量不符合活动要求!",Toast.LENGTH_SHORT).show();
                    return;
                }
                writeGoodsInfoToDatabase(this);//写入促销商品数据到数据库
                break;
            default:
                break;
        }
    }

    /**
     * 做最后的数据统计计算
     */
    public boolean makeTotalAccount(){
        int[] bpData = makeAccount(selflist,txtSelfCount,0);//计算本品的数据
        int[] zpData = makeAccount(givelist,txtGiveCount,1);//计算单品的数据
        for(SaleBuyOtherLevelTable item : saleLevelList){
            if(bpData[0]>=item.gmjs && bpData[1]>=item.gmss){
                if(zpData[0] == item.zsjs && zpData[1] == item.zsss) return true;
                return false;
            }
        }
        return false;
    }

    /**
     * 写入促销商品数据到数据库
     */
    public void writeGoodsInfoToDatabase(final Context context){
        new AsyncTask<Void,Void,Void>(){
            private String errMessage = null;
            private ProgressDialog dialog = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在提交数据...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                DbUtils dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
                SQLiteDatabase database = dbUtils.getDatabase();
                try {
                    database.beginTransaction();
                    for(ShoppingCartGoodsTable item : selflist){
                        if(item.hsdwsl != 0)
                            dbUtils.save(item);
                    }
                    for(ShoppingCartGoodsTable item : givelist){
                        if(item.hsdwsl != 0)
                            dbUtils.save(item);
                    }
                    database.setTransactionSuccessful();
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                database.endTransaction();
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage != null ){
                    Toast.makeText(context,"提交数据失败!原因: "+errMessage,Toast.LENGTH_SHORT).show();
                    return;
                }
                //数据提交成功，关闭当前页面
                ((Activity)context).setResult(RESULT_OK);
                goBack();//页面返回
            }
        }.execute();
    }

    /**
     * 做数据统计
     * @param list
     * @param txtAccount
     * @param type 0 - 本品  1 - 赠品
     */
    public int[] makeAccount(List<ShoppingCartGoodsTable> list,TextView txtAccount,int type){
        int pieceNum  = 0,singleNum = 0,hsgx = 1;
        Float totalMoney = 0f;
        String maxDw = "",minDw = "";//单位
        for(ShoppingCartGoodsTable item : list){
            pieceNum += item.xsdwsl;
            singleNum += item.xsdwss;
            maxDw = item.xsdw;
            minDw = item.hsdw;
            hsgx = item.hsgx;
            totalMoney += item.yfje;
        }
        pieceNum += singleNum / hsgx;
        if(type == 0) {//本品所具有的
            singleNum = singleNum % hsgx;
            txtTotalMoney.setText("合计金额：" + FormatUtils.exactNumber(totalMoney, "0.00") + "元");
        }
        txtAccount.setText((pieceNum==0?"":pieceNum+(type==1?"件":maxDw))+(singleNum==0?"":singleNum+(type==1?"散":minDw)));
        int[] result = new int[2];
        result[0] = pieceNum;
        result[1] = singleNum;
        return result;
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pgiveOther_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_MENU){
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
